// Labels Admin page scripts extracted from template
(function () {
  function ready(fn) {
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
      // If Bootstrap is already loaded, run the function immediately
      if (window.bootstrap) {
        fn();
      } else {
        // Otherwise wait for window load event
        window.addEventListener('load', fn);
      }
    } else {
      document.addEventListener('DOMContentLoaded', function() {
        if (window.bootstrap) {
          fn();
        } else {
          window.addEventListener('load', fn);
        }
      });
    }
  }

  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        if (cookie.substring(0, name.length + 1) === name + '=') {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

  function showAlert(type, message) {
    const div = document.createElement('div');
    div.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    div.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    div.innerHTML = `${message}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
    document.body.appendChild(div);
    setTimeout(() => div.remove(), 5000);
  }

  let currentTemplateId = null;

  function previewTemplate(templateId) {
    currentTemplateId = templateId;
    if (window.bootstrap) new window.bootstrap.Modal(document.getElementById('previewModal')).show();

    const content = document.getElementById('previewContent');
    if (content) {
      content.innerHTML = `
        <div class="spinner-border" role="status">
          <span class="visually-hidden">加载中...</span>
        </div>`;
    }

    fetch('/label-preview/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken'),
      },
      body: JSON.stringify({ template_id: templateId }),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          if (content) content.innerHTML = `<img src="${data.image_data}" alt="标签预览" class="img-fluid preview-image">`;
        } else {
          if (content)
            content.innerHTML = `
              <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i>
                预览失败: ${data.message || ''}
              </div>`;
        }
      })
      .catch((error) => {
        if (content)
          content.innerHTML = `
            <div class="alert alert-danger">
              <i class="fas fa-exclamation-triangle"></i>
              预览失败: ${error.message}
            </div>`;
      });
  }

  function editTemplate(templateId) {
    console.log('editTemplate called with ID:', templateId);
    
    // Instead of opening a modal, redirect to the designer with the template ID
    window.location.href = `/label-templates/designer/?template_id=${templateId}`;
  }

  function useTemplate(templateId) {
    window.location.href = `/label-print/?template_id=${templateId}`;
  }

  function duplicateTemplate(templateId) {
    if (!confirm('确定要复制这个模板吗？')) return;
    fetch(`/label-templates/${templateId}/duplicate/`, {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
      },
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          showAlert('success', '模板复制成功');
          setTimeout(() => location.reload(), 500);
        } else {
          showAlert('danger', data.message || '复制失败');
        }
      })
      .catch(() => showAlert('danger', '复制失败'));
  }

  function deleteTemplate(templateId) {
    if (!confirm('确定要删除这个模板吗？此操作不可恢复！')) return;
    fetch(`/label-templates/${templateId}/delete/`, {
      method: 'DELETE',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
      },
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          showAlert('success', '模板删除成功');
          setTimeout(() => location.reload(), 500);
        } else {
          showAlert('danger', data.message || '删除失败');
        }
      })
      .catch(() => showAlert('danger', '删除失败'));
  }

  function createQuickTemplate(type) {
    const templateTypes = { asset: '资产标签模板', equipment: '设备标签模板', location: '位置标签模板' };
    const templateName = templateTypes[type] || '快速模板';
    window.location.href = `/label-templates/designer/?quick_type=${encodeURIComponent(type)}&name=${encodeURIComponent(templateName)}`;
  }

  function importTemplates() {
    if (window.bootstrap) new window.bootstrap.Modal(document.getElementById('importModal')).show();
  }

  function exportTemplates() {
    if (window.bootstrap) new window.bootstrap.Modal(document.getElementById('exportModal')).show();
  }

  function confirmImport() {
    const fileInput = document.getElementById('importFile');
    const overwrite = document.getElementById('importOverwrite').checked;
    if (!fileInput || !fileInput.files.length) {
      showAlert('warning', '请选择要导入的模板文件');
      return;
    }
    const formData = new FormData();
    formData.append('template_file', fileInput.files[0]);
    formData.append('overwrite', overwrite);

    fetch('/assets/labels/templates/import/', {
      method: 'POST',
      headers: {
        'X-CSRFToken': getCookie('csrftoken'),
      },
      body: formData,
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.success) {
          showAlert('success', `成功导入 ${data.imported_count} 个模板`);
          if (window.bootstrap) window.bootstrap.Modal.getInstance(document.getElementById('importModal'))?.hide();
          setTimeout(() => location.reload(), 1000);
        } else {
          showAlert('danger', data.message || '导入失败');
        }
      })
      .catch((e) => showAlert('danger', '导入失败：' + e.message));
  }

  function confirmExport() {
    const format = document.getElementById('exportFormat').value;
  }

  function printPreview() {
    if (currentTemplateId) {
      useTemplate(currentTemplateId);
    }
  }

  // Form Handlers
  // ============

  /**
   * Handle save template form submission
   * @param {Event} e - The form submission event
   */
  function handleSaveTemplate(e) {
    e.preventDefault();
    
    const form = document.getElementById('edit-template-form');
    if (!form) {
      console.error('Edit template form not found');
      return;
    }

    const formData = new FormData(form);
    const templateId = document.getElementById('edit-template-id')?.value;
    const submitBtn = document.getElementById('save-template-btn');

    if (!templateId || !submitBtn) {
      console.error('Required elements not found');
      return;
    }

    const originalBtnText = submitBtn.innerHTML;

    // Show loading state
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
    submitBtn.disabled = true;

    // Prepare data object from form data
    const data = {};
    formData.forEach((value, key) => {
      data[key] = value;
    });

    // Send update request
    fetch(`/api/label-templates/${templateId}/`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken')
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        return response.json().then(err => {
          throw new Error(err.message || 'Failed to update template');
        });
      }
      return response.json();
    })
    .then(data => {
      showAlert('success', '模板更新成功');
      // Close the modal
      const modal = bootstrap.Modal.getInstance(document.getElementById('editTemplateModal'));
      if (modal) modal.hide();
      // Reload the page to show changes
      window.location.reload();
    })
    .catch(error => {
      console.error('Error:', error);
      showAlert('danger', '保存失败: ' + error.message);
    })
    .finally(() => {
      if (submitBtn) {
        submitBtn.innerHTML = originalBtnText;
        submitBtn.disabled = false;
      }
    });
  }

  // Event Handlers
  // =============

  /**
   * Initialize all event handlers
   */
  function initializeEventHandlers() {
    console.log('Initializing event handlers...');
    console.log('jQuery available:', !!window.jQuery);
    console.log('Bootstrap available:', !!window.bootstrap);

    // Save button event listener
    const saveBtn = document.getElementById('save-template-btn');
    if (saveBtn) {
      saveBtn.removeEventListener('click', handleSaveTemplate);
      saveBtn.addEventListener('click', handleSaveTemplate);
    }

    // Initialize modals
    const editModal = document.getElementById('editTemplateModal');
    if (editModal && window.bootstrap) {
      if (!bootstrap.Modal.getInstance(editModal)) {
        new bootstrap.Modal(editModal);
      }
    }

    // Global click handler for template actions
    document.addEventListener('click', (e) => {
      // Handle template action buttons
      const actionBtn = e.target.closest('[data-action]');
      if (actionBtn) {
        const action = actionBtn.dataset.action;
        const templateId = actionBtn.dataset.templateId;
        
        switch (action) {
          case 'edit':
            editTemplate(templateId);
            break;
          case 'preview':
            previewTemplate(templateId);
            break;
          case 'use':
            useTemplate(templateId);
            break;
          case 'duplicate':
            duplicateTemplate(templateId);
            break;
          case 'delete':
            deleteTemplate(templateId);
            break;
        }
      }

      // Handle quick actions
      const quickBtn = e.target.closest('.quick-action-btn');
      if (quickBtn) {
        const quickType = quickBtn.dataset.quickType;
        const action = quickBtn.dataset.action;
        
        if (quickType) {
          createQuickTemplate(quickType);
        } else if (action === 'import') {
          importTemplates();
        } else if (action === 'export') {
          exportTemplates();
        }
      }
    });
  }

  // Global Exports
  // =============
  window.previewTemplate = previewTemplate;
  window.editTemplate = editTemplate;
  window.useTemplate = useTemplate;
  window.duplicateTemplate = duplicateTemplate;
  window.deleteTemplate = deleteTemplate;
  window.createQuickTemplate = createQuickTemplate;
  window.importTemplates = importTemplates;
  window.exportTemplates = exportTemplates;
  window.confirmImport = confirmImport;
  window.confirmExport = confirmExport;
  window.printPreview = printPreview;
  window.handleSaveTemplate = handleSaveTemplate;
  window.initializeEventHandlers = initializeEventHandlers;

  // Initialization
  // =============
  // Check if Bootstrap is loaded and initialize
  function checkBootstrapAndInitialize() {
    if (window.bootstrap) {
      initializeEventHandlers();
      
      // Initialize modals
      const modals = document.querySelectorAll('.modal');
      modals.forEach(modal => {
        if (!bootstrap.Modal.getInstance(modal)) {
          new bootstrap.Modal(modal);
        }
      });
      
      // Initialize tooltips
      const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
      tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
      });
      
      console.log('Bootstrap components initialized');
    } else {
      console.log('Bootstrap not loaded yet, waiting...');
      setTimeout(checkBootstrapAndInitialize, 100);
    }
  }
  
  // Initialize event handlers when the DOM is fully loaded
  ready(function() {
    console.log('DOM fully loaded');
    
    // Add global click handler for template action buttons
    document.addEventListener('click', function(e) {
      console.log('Click event detected', e.target);
      const btn = e.target.closest('.btn-template-action');
      console.log('Button found:', btn);
      
      if (btn) {
        const action = btn.dataset.action;
        const templateId = btn.dataset.templateId;
        console.log('Action:', action, 'Template ID:', templateId);
        
        if (action === 'edit') editTemplate(templateId);
        else if (action === 'preview') previewTemplate(templateId);
        else if (action === 'use') useTemplate(templateId);
        else if (action === 'duplicate') duplicateTemplate(templateId);
        else if (action === 'delete') deleteTemplate(templateId);
      }

      const quickBtn = e.target.closest('.quick-action-btn');
      if (quickBtn) {
        const quickType = quickBtn.dataset.quickType;
        const action = quickBtn.dataset.action;
        if (quickType) createQuickTemplate(quickType);
        else if (action === 'import') importTemplates();
        else if (action === 'export') exportTemplates();
      }
    });

    // Start initialization
    console.log('Document ready, checking for Bootstrap...');
    checkBootstrapAndInitialize();
  });
})();
